package com.example.demo.controller;

import com.example.demo.entiy.Article;
import com.example.demo.service.ArticleService;
import com.example.demo.service.StatisticService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.Comparator;
import java.util.List;


@org.springframework.stereotype.Controller
public class IndexController {

    @Autowired
    ArticleService articleService;

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    StatisticService statisticService;


    @GetMapping({"/", "/{pageNum}"})
    public String index(Model model,
                        @PathVariable(value = "pageNum", required = false) Integer pageNum) {
        int i = 1;
        if (pageNum == null) {
            pageNum = 1;
        }
        //把所有文章数据的属性已经点击量放入redis缓存中
        redisTemplate.opsForValue().set("articles",articleService.getArticleListAndHits());
        PageHelper.startPage(pageNum, 4);
        List<Article> articleList = articleService.getArticleList();
        model.addAttribute("articleList", articleList);
        PageInfo pageInfo = new PageInfo(articleList);
        model.addAttribute("pageInfo", pageInfo);
        //阅读排行榜
        PageHelper.startPage(1, 10);
        List<Article> articles = articleService.getArticleOrderDesc();
        //显示排序之后的顺序
        for (Article article : articles) {
            article.setIdNumber(i);
            i++;
        }
        model.addAttribute("articles", articles);
//        PageInfo pageInfoOrder = new PageInfo(articles);
//        model.addAttribute("pageInfoOrder", pageInfoOrder);
        return "/client/index";
    }


    /**
     * 定时任务： 程序启动后自动执行
     * cron： 根据规定的时间执行任务 （秒 分 时 日 月 星期）
     */
//    @Scheduled(cron = "* * 23 * * *")
//    @Scheduled(fixedDelay = 10000)
    public void redisUpdateDatabase() {
        List<Article> articles = (List<Article>) redisTemplate.opsForValue().get("articles");
        for (Article article : articles) {
            try {
                statisticService.setHitsByArticleId(article.getHits(), article.getId());
            } catch (Exception e) {
                System.out.println("===========");
                System.out.println(e.getMessage());
                System.out.println("===========");
            }
        }
//        System.out.println("测试10秒钟一次");
    }

}


